# -*- coding: utf-8 -*-
import base64
import os
import urllib
import urllib2
import numpy as np
import json
import numpy as np
import cv2.cv as cv
import cv2
import random

def to_canny(file_path):
	img = cv2.imread(file_path, 0)  # Canny只能处理灰度图，所以将读取的图像转成灰度图
	img = cv2.GaussianBlur(img, (5, 5), 0)  # 高斯平滑处理原图像降噪
	canny = cv2.Canny(img, 30, 100)  # apertureSize默认为3
	return canny

	# cv2.imshow('Canny', canny)
	# cv2.imwrite('dou13_canny.jpg',canny)
	# cv2.waitKey(0)
	# cv2.destroyAllWindows()


APP_ID = '9572873'
API_KEY = 'c7vrv6HyjGNVm1zAfOAbdNGu'
SECRET_KEY = 'bWiOaZapd4xmD87m5qTZtfT2IGxT4WO3'

def AuthService():
    # 获取token地址
    authHost = "https://aip.baidubce.com/oauth/2.0/token?"
    # 官网获取的 API Key
    clientId = API_KEY
    # 官网获取的 Secret Key
    clientSecret = SECRET_KEY
    getAccessTokenUrl = authHost + "grant_type=client_credentials" + "&client_id=" + clientId + "&client_secret=" + clientSecret
    request = urllib2.Request(getAccessTokenUrl)
    response_data = urllib2.urlopen(request)
    params = json.loads(response_data.read())
    return params["access_token"]


# print AuthService()

def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

def baidu_detect(file_path):
	detectUrl = "https://aip.baidubce.com/rest/2.0/face/v1/detect?access_token="+AuthService()
	params = {"max_face_num": 1, "face_fields": "age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities",
			  "image": base64.b64encode(get_file_content(file_path))}
	params = urllib.urlencode(params)
	request = urllib2.Request(url=detectUrl, data=params)
	request.add_header('Content-Type', 'application/x-www-form-urlencoded')
	response = urllib2.urlopen(request)
	content = response.read()
	return content

# def crop_img():
#     if baidu_detect():
#         # print baidu_detect()
#         hjson = json.loads(baidu_detect())
#         left = hjson['result'][0]['location']['left']
#         top = hjson['result'][0]['location']['top']
#         width = hjson['result'][0]['location']['width']
#         height = hjson['result'][0]['location']['height']
#         box = (left, top,
#               left + width,
#                top + height,)
#         crop_path = (os.getcwd() + '/data/crop/')
#         image_crop = Image.open(crop_path + "dou13.jpg")
#         # image_crop = image_crop.rotate(-90)
#         # roi = image_crop.crop(box)
#         # image = roi.resize([1960, 1960])
#         # plt.imshow(roi)
#         # plt.show()
#         # img_d = ImageDraw.Draw(image_crop)
#         # img_d.rectangle((left, top, left+width,
#         #                  top + height), outline=(255, 0, 0, 128))
#         # plt.imshow(image_crop)
#         # plt.show()
#
#         # 先按照原图10*10去切，切完之后resize
#         img_arr = []
#         for i in range(10):
#             for j in range(10):
#                 box = (left+j*(width/10), top+i*(height/10), left+(j+1)*(width/10), top+(i+1)*(height/10))
#                 roi = image_crop.crop(box)
#                 roi = roi.resize([196, 196])
#                 roi = np.array(roi)
#                 img_arr.append(roi)
#
#         # for k in range(len(img_arr)):
#         #     plt.imshow(img_arr[k])
#         #     plt.show()
#     return img_arr, left, top, width, height

# crop_img()

# 0～12是13个脸周围的坐标
# 将canny后的脸利用百度检测的结果进一步处理一下
def crop_face(file_path):

    if baidu_detect(file_path):
        # print type(baidu_detect(file_path))
        hjson = json.loads(baidu_detect(file_path))
        print hjson

        # 脸周边
        x1 = hjson['result'][0]['landmark72'][0]['x']
        y1 = hjson['result'][0]['landmark72'][0]['y']
        x2 = hjson['result'][0]['landmark72'][1]['x']
        y2 = hjson['result'][0]['landmark72'][1]['y']
        x3 = hjson['result'][0]['landmark72'][2]['x']
        y3 = hjson['result'][0]['landmark72'][2]['y']
        x4 = hjson['result'][0]['landmark72'][3]['x']
        y4 = hjson['result'][0]['landmark72'][3]['y']
        x5 = hjson['result'][0]['landmark72'][4]['x']
        y5 = hjson['result'][0]['landmark72'][4]['y']
        x6 = hjson['result'][0]['landmark72'][5]['x']
        y6 = hjson['result'][0]['landmark72'][5]['y']
        x7 = hjson['result'][0]['landmark72'][6]['x']
        y7 = hjson['result'][0]['landmark72'][6]['y']
        x8 = hjson['result'][0]['landmark72'][7]['x']
        y8 = hjson['result'][0]['landmark72'][7]['y']
        x9 = hjson['result'][0]['landmark72'][8]['x']
        y9 = hjson['result'][0]['landmark72'][8]['y']
        x10 = hjson['result'][0]['landmark72'][9]['x']
        y10 = hjson['result'][0]['landmark72'][9]['y']
        x11 = hjson['result'][0]['landmark72'][10]['x']
        y11 = hjson['result'][0]['landmark72'][10]['y']
        x12 = hjson['result'][0]['landmark72'][11]['x']
        y12 = hjson['result'][0]['landmark72'][11]['y']
        x13 = hjson['result'][0]['landmark72'][12]['x']
        y13 = hjson['result'][0]['landmark72'][12]['y']

		# 鼻子部分
        x49 = hjson['result'][0]['landmark72'][48]['x']
        y49 = hjson['result'][0]['landmark72'][48]['y']
        x50 = hjson['result'][0]['landmark72'][49]['x']
        y50 = hjson['result'][0]['landmark72'][49]['y']
        x51 = hjson['result'][0]['landmark72'][50]['x']
        y51 = hjson['result'][0]['landmark72'][50]['y']
        x52 = hjson['result'][0]['landmark72'][51]['x']
        y52 = hjson['result'][0]['landmark72'][51]['y']
        x53 = hjson['result'][0]['landmark72'][52]['x']
        y53 = hjson['result'][0]['landmark72'][52]['y']
        x54 = hjson['result'][0]['landmark72'][53]['x']
        y54 = hjson['result'][0]['landmark72'][53]['y']
        x55 = hjson['result'][0]['landmark72'][54]['x']
        y55 = hjson['result'][0]['landmark72'][54]['y']

		# 嘴巴部分
        x59 = hjson['result'][0]['landmark72'][58]['x']
        y59 = hjson['result'][0]['landmark72'][58]['y']
        x60 = hjson['result'][0]['landmark72'][59]['x']
        y60 = hjson['result'][0]['landmark72'][59]['y']
        x61 = hjson['result'][0]['landmark72'][60]['x']
        y61 = hjson['result'][0]['landmark72'][60]['y']
        x62 = hjson['result'][0]['landmark72'][61]['x']
        y62 = hjson['result'][0]['landmark72'][61]['y']
        x63 = hjson['result'][0]['landmark72'][62]['x']
        y63 = hjson['result'][0]['landmark72'][62]['y']
        x64 = hjson['result'][0]['landmark72'][63]['x']
        y64 = hjson['result'][0]['landmark72'][63]['y']
        x65 = hjson['result'][0]['landmark72'][64]['x']
        y65 = hjson['result'][0]['landmark72'][64]['y']

        img1 = (to_canny(file_path))
        img = hole_filler(img1)

        # print img.shape
        # cv2.line(img,(x1,y1),(x2,y2),255,1)
        cv2.line(img,(x2+10,y2),(x3+10,y3),255,1)
        cv2.line(img,(x3+10,y3),(x4+10,y4),255,1)
        cv2.line(img,(x4+10,y4),(x5+10,y5),255,1)
        cv2.line(img,(x5+10,y5),(x6+10,y6),255,1)
        cv2.line(img,(x6+10,y6),(x7,y7),255,1)
        cv2.line(img,(x7,y7),(x8-10,y8),255,1)
        cv2.line(img,(x8-10,y8),(x9-10,y9),255,1)
        cv2.line(img,(x9-10,y9),(x10-10,y10),255,1)
        cv2.line(img,(x10-10,y10),(x11-10,y11),255,1)
        cv2.line(img,(x11-10,y11),(x12-10,y12),255,1)
        # cv2.line(img,(x12,y12),(x13,y13),255,1)
        cv2.line(img,(x2+10,y2),(x12-10,y12),255,1)
        print x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12

        h, w = img.shape[:2]
        mask = np.zeros((h + 2, w + 2), np.uint8)
        cv2.floodFill(img, mask, (0, 0), (255,255,255))

        # nose
        # (x51-10,y50-10)(x54+10,y54+10)
        # cv2.rectangle(img,(x51-10,y50-10),(x54+10,y54+15),255, 1)
        for i in range(x51-10, x54+10):
            for j in range(y50-10, y54+15):
                img[j, i] = 255

        # cv2.rectangle(img, (x59-10, y59-10), (x63+10,y65+10), 255, 1)
        for i in range(x59-10, x63+10):
            for j in range(y59-10, y65):
                img[j, i] = 255

        img_out = img1 | img
        # cv2.imshow('img',img)
        # cv2.imshow('img1',img1)
        # cv2.imshow('img_out', img_out)
        # hough_transfer(img_out)
        print os.getcwd()
        cv2.imwrite(os.getcwd()+'/images/'+'img_out.jpg',img_out)
        circle_json = hough_transfer(os.getcwd()+'/images/'+'img_out.jpg')
        # print img_out
        # print cv2.imread('img_out.jpg')
        # cv2.imshow('out',img_out)
        # cv2.waitKey(0)
        return circle_json

# 复制一张canny脸的纯黑色图
def hole_filler(img):
    # Copy the thresholded image.
    im_floodfill = img.copy()
    # Mask used to flood filling.
    # Notice the size needs to be 2 pixels than the image.
    h, w = img.shape[:2]
    for i in range(w):
        for j in range(h):
            im_floodfill[j, i] = 0

    return im_floodfill

def set_default(obj):
    if isinstance(obj, set):
        return list(obj)
    raise TypeError

def hough_transfer(path):
    img = cv2.imread(path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)#灰度图像
    img1 = cv2.imread(os.getcwd()+'/'+'dou21.jpg')

    # plt.subplot(121),plt.imshow(gray,'gray')
    # plt.xticks([]),plt.yticks([])
    #hough transform
    circles1 = cv2.HoughCircles(gray,cv.CV_HOUGH_GRADIENT,1,
    100,param1=100,param2=10,minRadius=2,maxRadius=15)
    print circles1

    try:
        circles = circles1[0, :, :]
        circles = np.uint16(np.around(circles))  # 四舍五入，取整
        # print circles
        arr = []
        for i in circles[:]:
            cv2.circle(img1, (i[0], i[1]), i[2], (255, 0, 0), 5)  # 画圆
            cv2.circle(img1, (i[0], i[1]), 2, (255, 0, 255), 10)  # 画圆心
            data = {'x':int(i[0]),'y':int(i[1])}
            arr.append(data)
        print json.dumps(arr)
        cv2.imwrite('dou21_res.jpg',img1)
        return str(arr)
        # return arr
        # return json.dumps(arr,ensure_ascii=False, encoding='UTF-8')
    except:
        print 'no data'
        return json.dumps([])

# crop_face(os.getcwd()+'/'+'dou15.jpg')
# print os.getcwd()
# print cv2.__version__

# 过滤颜色
def filter_color():
    img = cv2.imread(os.getcwd()+'/'+'dou13.jpg')
    print img[548,306,0]
    print img[548,306,1]
    print img[548,306,2]